class ResourceType extends React.Component {
    constructor(props) {
        super(props);
        this.page = 1;
        this.state = {
            treeList: [],
            modalList: [],
            typelist: [],
            selectParent: {
                parent_name: '',
                parent_code: ''
            },
            inputValues: {
                type_id: '',
                parent_codes: '',
                type_name: '',
                type_code: '',
                minConut: '',
                maxConut: '',
                sortEncoding: 0,
                description: ''
            },
            customContent: {},
            customView: [],
            customPropertyIds: [],
            customPropertyPrivateIds: [],
            customContentIds: [],
            addCustomType: {
                customType: '',
                callback: (ids) => {
                }
            }
        }
    }

    componentDidMount() {
        this.queryTreeList();
        let isNum = /^[0-9]+$/;
        let regCode = /^[a-zA-Z_0-9]+$/;
        this.verify = {
            type_code: (value) => {
                if (value.length < 2) {
                    return '分类编码至少得2个字符!';
                }
                if (!regCode.test(value)) {
                    return '分类编码只能是英文，数字，下划线组成！';
                }
            },
            minConut: (value) => {
                if (value && !isNum.test(value)) {
                    return '最小条目必须是数字！';
                }
            },
            maxConut: (value) => {
                if (value && !isNum.test(value)) {
                    return '最大条目必须是数字！';
                }
                if (this.state.inputValues.minConut && value < this.state.inputValues.minConut) {
                    return '最大条目必须大于最小条目!';
                }
            },
            sortEncoding: (value) => {
                if (value && !isNum.test(value)) {
                    return '排序编码必须是数字！';
                }
            }
        };
    }

    queryTreeList() {
        postJson("/cms/resource/type/queryResourceTypes.x", null, (data) => {
            let treeList = this.refs.tree.getNodes(data.data, "-1", 'parent_code', 'type_code', 'type_name');
            let modalList = this.refs.treeModal.getNodes(data.data, "-1", 'parent_code', 'type_code', 'type_name');
            modalList.unshift({name: '无'});
            console.log("modalList", modalList);
            this.setState({
                typelist: data.data,
                treeList: treeList,
                modalList: modalList
            });
        });
    }

    onSelected(data) {
        console.log("data", data);
        let selectParent = {
            parent_name: '',
            parent_code: ''
        };
        for (let i in this.state.typelist) {
            if (this.state.typelist[i].type_code === data.parent_code) {
                selectParent = {
                    parent_name: this.state.typelist[i].type_name,
                    parent_code: this.state.typelist[i].type_code
                };
                break;
            }
        }
        this.setState({
            selectParent: selectParent,
            inputValues: {
                type_id: data.type_id,
                parent_codes: '',
                type_name: data.type_name,
                type_code: data.type_code,
                minConut: data.minConut,
                maxConut: data.maxConut,
                sortEncoding: data.sortEncoding,
                description: data.description
            }
        }, () => {
            this.customView(this.state.selectParent.parent_code, data.customProperty);
            this.getCustomTypeByIds('CUSTOM_TYPE', data.customContentId);
            this.getCustomTypeByIds('CUSTOM_PROPERTY', data.customPropertyId);
            this.getCustomTypeByIds('CUSTOM_PROPERTY_PRIVATE', data.customPropertyPrivateId);
        });
    }

    customChange(type, value) {
        this.state.customContent[type] = value;
        this.setState({});
    }

    inputChange(type, value) {
        this.state.inputValues[type] = value;
        this.setState({});
    }

    customView(parentCode, customPropertys) {
        if (customPropertys)
            customPropertys = JSON.parse(customPropertys);
        this.state.customView = [];
        for (let i in this.state.typelist) {
            if (this.state.typelist[i].type_code === parentCode && this.state.typelist[i].customPropertyId) {
                let param = {};
                param.isPage = false;
                param.isAnalysisCustomContent = true;
                param.customTypeId = this.state.typelist[i].customPropertyId;
                postJson("/cms/resource/queryCustomTypeList.x", $.param(param), (data) => {
                    let customTypeList = data.data.list;
                    for (let i in customTypeList) {
                        let customContents = customTypeList[i].customContents;
                        for (let j in customContents) {
                            let customContent = customContents[j];
                            if (customContent && customContent.customType === 'CMS_CUSTOM_SORT') {
                                let option = [];
                                let customValue = '';
                                if (customContent.spinnerMap) {
                                    for (let key in customContent.spinnerMap) {
                                        for (let k in customPropertys) {
                                            if (customPropertys[k].customKey === customContent.customKey &&
                                                customPropertys[k].customValue === key) {
                                                customValue = customPropertys[k].customValue;
                                                break;
                                            }
                                        }
                                        option.push(<option value={key}>{customContent.spinnerMap[key]}</option>);
                                    }
                                } else {
                                    option.push(<option value="-1">无</option>);
                                }
                                this.state.customContent[customContent.customKey] = {
                                    customValue: customValue,
                                    customDescribe: customContent.customDescribe
                                };
                                this.state.customView.push(<Item>
                                    <Label>{customContent.customName}</Label>
                                    <Select onChange={(data) => this.customChange(customContent.customKey, data)}
                                            value={this.state.customContent[customContent.customKey].customValue}>
                                        {[...option]}
                                    </Select>
                                </Item>);
                            } else if (customContent) {
                                let value = '';
                                for (let l in customPropertys) {
                                    if (customPropertys[l].customKey === customContent.customKey) {
                                        value = customPropertys[l].customValue;
                                        break;
                                    }
                                }
                                this.state.customContent[customContent.customKey] = {
                                    customValue: value,
                                    customDescribe: customContent.customDescribe
                                };
                                this.state.customView.push(<Item>
                                    <Label>{customContent.customName}</Label>
                                    <Input type="text"
                                           block={true}
                                           value={this.state.customContent[customContent.customKey].customValue}
                                           ref={customContent.customKey}
                                           onChange={(value) => this.customChange(customContent.customKey, value)}
                                    />
                                </Item>);
                            }
                        }
                    }
                    this.setState({});
                });
            }
        }
        this.setState({});
    }

    getCustomTypeByIds(type, customContentId) {
        this.state.customPropertyIds = [];
        this.state.customPropertyPrivateIds = [];
        this.state.customContentIds = [];
        if (customContentId) {
            let param = {};
            param.isPage = false;
            param.customTypeId = customContentId;
            postJson("/cms/resource/queryCustomTypeList.x", $.param(param), (data) => {
                if (type === 'CUSTOM_PROPERTY') {
                    this.state.customPropertyIds = data.data.list;
                } else if (type === 'CUSTOM_PROPERTY_PRIVATE') {
                    this.state.customPropertyPrivateIds = data.data.list;
                } else {
                    this.state.customContentIds = data.data.list;
                }
                this.setState({});
            });
        } else {
            this.setState({});
        }
    }

    addCustomType(customType, callback) {
        this.setState({
            addCustomType: {
                customType: customType,
                callback: (ids) => callback(ids)
            }
        }, () => {
            this.refs.CustomTypeListModal.show();
        });
    }

    render() {
        return <Frame header="编辑资源类型" headerBtns={
            <SecurityCheck roles="admin">
                <HeaderBtn onClick={() => this.addAppConfigType()}>
                    清空缓存</HeaderBtn>
            </SecurityCheck>}>
            <div style={{marginTop: '15px', width: '20%', border: '1px solid #ddd', display: 'inline-block'}}>
                <Tree ref="tree" nodes={this.state.treeList} errorStr="无上级节点"
                      onItemSelect={(data) => this.onSelected(data)}>
                </Tree>
            </div>
            <div style={{display: 'inline-block', width: '75%', verticalAlign: 'top', paddingLeft: '20px'}}>
                <Form id="form" type="pane">
                    <Input type="hidden" value={this.state.inputValues.type_id}/>
                    <Input type="hidden" value={this.state.inputValues.parent_codes}/>
                    <Item>
                        <Label>上级分类</Label>
                        <Input type="text"
                               readonly="readonly"
                               ref="parent_name"
                               value={this.state.selectParent.parent_name}
                               placeholder="请选择上级分类"
                               onClick={() => this.refs.treeModal.show({typeData: this.refs.parent_name.refs.input})}
                        />
                    </Item>
                    <Item>
                        <Label>分类名称</Label>
                        <Input type="text"
                               lay-verify="type_name"
                               value={this.state.inputValues.type_name}
                               placeholder="请输入分类名称"
                               onChange={(value) => this.inputChange('type_name', value)}
                        />
                    </Item>
                    <Item>
                        <Label>分类编码</Label>
                        <Input type="text"
                               ref="type_code"
                               lay-verify="type_code"
                               value={this.state.inputValues.type_code}
                               placeholder="请输入英文分类编码"
                               onChange={(value) => this.inputChange('type_code', value)}
                        />
                    </Item>
                    <Item>
                        <Label>条目范围</Label>
                        <Input type="text"
                               ref="minConut"
                               lay-verify="minConut"
                               value={this.state.inputValues.minConut}
                               placeholder="最小条目"
                               onChange={(value) => this.inputChange('minConut', value)}
                        />
                        <Input type="text"
                               ref="maxConut"
                               lay-verify="maxConut"
                               value={this.state.inputValues.maxConut}
                               placeholder="最大条目"
                               onChange={(value) => this.inputChange('maxConut', value)}
                        />
                    </Item>
                    <Item>
                        <Label>排序编号</Label>
                        <Input type="text"
                               ref="sortEncoding"
                               lay-verify="sortEncoding"
                               value={this.state.inputValues.sortEncoding}
                               placeholder="请输入排序编号"
                               onChange={(value) => this.inputChange('sortEncoding', value)}
                        />
                    </Item>
                    <Item>
                        <Label>描述</Label>
                        <Input type="text"
                               block={true}
                               ref="description"
                               value={this.state.inputValues.description}
                               placeholder="请输入描述"
                               onChange={(value) => this.inputChange('description', value)}
                        />
                    </Item>
                    {[...this.state.customView]}
                    <Item className="layui-form-text">
                        <Label>添加子节点自定义属性&nbsp;&nbsp;【添加子节点自定义属性后，所有子节点将拥有该属性】</Label>
                        <Tab titles={['共有属性', '私有属性']} ids={['0', '1']} type="brief">
                            <TabItem show="true">
                                <div style={{
                                    background: '#FFFFFF',
                                    paddingTop: '10px',
                                    paddingLeft: '10px',
                                    paddingRight: '10px'
                                }}>
                                    <Button size="xs"
                                            onClick={() => this.addCustomType('CUSTOM_PROPERTY', (ids) => {
                                                    this.setState({
                                                        customPropertyIds: ids
                                                    })
                                                }
                                            )}>
                                        添加共有属性
                                    </Button>

                                    <hr style={{background: '#00acd6'}}/>
                                    <div id="customPropertyPerms"
                                         className="layui-input-block"
                                         style={{padding: '10px'}}>
                                        {this.state.customPropertyIds.map((array, index) => {
                                            return <div>
                                                <div style={{float: 'left', marginRight: '20px'}}>
                                                    <div>
                                                        自定义分类名称： {array.custom_type_name}
                                                    </div>
                                                </div>

                                                <Button size="xs" btnType="danger"
                                                        onClick={() => {
                                                            this.state.customPropertyIds.splice(index, 1);
                                                            this.setState({})
                                                        }}>删除</Button>
                                                <Button size="xs"
                                                        onClick={() => this.edit(array)}>查看</Button>
                                                <hr/>
                                            </div>
                                        })}
                                    </div>
                                </div>
                            </TabItem>
                            <TabItem>
                                <div
                                    style={{
                                        background: '#FFFFFF',
                                        paddingTop: '10px',
                                        paddingLeft: '10px',
                                        paddingRight: '10px'
                                    }}>
                                    <Button size="xs"
                                            onClick={() => this.addCustomType('CUSTOM_PROPERTY_PRIVATE', (ids) => {
                                                this.setState({
                                                    customPropertyPrivateIds: ids
                                                })
                                            })}>
                                        添加私有属性
                                    </Button>
                                    <hr style={{background: '#00acd6'}}/>
                                    <div id="customPropertyPrivatePerms" className="layui-input-block"
                                         style={{padding: '10px'}}>
                                        {this.state.customPropertyPrivateIds.map((array, index) => {
                                            console.log("index", index);
                                            return <div>
                                                <div style={{float: 'left', marginRight: '20px'}}>
                                                    <div>
                                                        自定义分类名称： {array.custom_type_name}
                                                    </div>
                                                </div>

                                                <Button size="xs" btnType="danger"

                                                        onClick={() => {
                                                            this.state.customPropertyPrivateIds.splice(index, 1);
                                                            this.setState({})
                                                        }}>删除</Button>
                                                <Button size="xs"
                                                        onClick={() => this.edit(array)}>查看</Button>
                                                <hr/>
                                            </div>
                                        })}
                                    </div>
                                </div>
                            </TabItem>
                        </Tab>
                    </Item>
                    <Item className="layui-form-text">
                        <Label>选择自定义类型&nbsp;&nbsp;【自定义资源类型表示该资源可选择的几种格式】</Label>
                        <div style={{
                            background: '#FFFFFF',
                            paddingTop: '10px',
                            paddingLeft: '10px',
                            paddingRight: '10px'
                        }}>
                            <Button size="xs"
                                    onClick={() => this.addCustomType('CUSTOM_TYPE', (ids) => {
                                            this.setState({
                                                customContentIds: ids
                                            })
                                        }
                                    )}>
                                类型列表
                            </Button>
                            <hr style={{background: '#00acd6'}}/>
                            <div id="customTypePerms"
                                 className="layui-input-block"
                                 style={{padding: '10px'}}>

                                {this.state.customContentIds.map((array, index) => {
                                    return <div>
                                        <div style={{float: 'left', marginRight: '20px'}}>
                                            <div>
                                                自定义分类名称： {array.custom_type_name}
                                            </div>
                                        </div>
                                        <Button size="xs" btnType="danger"
                                                onClick={() => {
                                                    this.state.customContentIds.splice(index, 1);
                                                    this.setState({})
                                                }}>删除</Button>
                                        <Button size="xs"
                                                onClick={() => this.edit(array)}>查看</Button>
                                        <hr/>
                                    </div>
                                })}

                            </div>
                        </div>
                    </Item>
                </Form>
            </div>

            <TreeModal ref="treeModal" nodes={this.state.modalList} errorStr="无上级菜单"
                       onSelected={(string, data) => {
                           this.setState({
                               selectParent: {
                                   parent_name: data.type_name ? data.type_name : '',
                                   parent_code: data.type_code ? data.type_code : ''
                               }
                           }, () => {
                               this.customView(this.state.selectParent.parent_code);
                           });
                       }}>
            </TreeModal>

            <CustomTypeListModal ref="CustomTypeListModal" customType={this.state.addCustomType.customType}
                                 callback={(ids) => this.state.addCustomType.callback(ids)}/>

        </Frame>
    }
}

ReactDOM.render(
    <ResourceType/>,
    document.getElementById('root')
);
